package com.knowledgepoint.study.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.knowledgepoint.study.common.api.CommonPage;
import com.knowledgepoint.study.common.api.CommonResult;
import com.knowledgepoint.study.model.entity.KnowledgePointArticle;
import com.knowledgepoint.study.service.KnowledgePointArticleService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 知识点文章管理
 */
@RestController
@RequestMapping("/knowledge/article")
@Api(tags = "知识点文章管理")
public class KnowledgePointArticleController {

    @Autowired
    private KnowledgePointArticleService articleService;

    @ApiOperation(value = "创建文章", notes = "创建一篇新的知识点文章，返回文章ID")
    @ApiResponses({
        @ApiResponse(code = 200, message = "创建成功"),
        @ApiResponse(code = 400, message = "参数错误"),
        @ApiResponse(code = 500, message = "系统内部错误")
    })
    @PostMapping("/create")
    public CommonResult<Integer> create(
            @ApiParam(value = "文章信息", required = true)
            @Validated @RequestBody KnowledgePointArticle article) {
        Integer articleId = articleService.addAndReturnId(article);
        return articleId != null ? CommonResult.success(articleId, "创建成功") : CommonResult.failed("创建失败");
    }

    @ApiOperation(value = "修改文章", notes = "根据ID修改知识点文章信息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "操作成功"),
        @ApiResponse(code = 400, message = "参数错误"),
        @ApiResponse(code = 404, message = "资源不存在"),
        @ApiResponse(code = 500, message = "系统内部错误")
    })
    @PostMapping("/update/{id}")
    public CommonResult<Void> update(
            @ApiParam(value = "文章ID", required = true) @PathVariable Integer id,
            @ApiParam(value = "文章信息", required = true) @Validated @RequestBody KnowledgePointArticle article) {
        article.setId(id);
        boolean success = articleService.update(article);
        return success ? CommonResult.success(null, "修改成功") : CommonResult.failed("修改失败");
    }

    @ApiOperation(value = "删除文章", notes = "根据ID删除知识点文章")
    @ApiResponses({
        @ApiResponse(code = 200, message = "删除成功"),
        @ApiResponse(code = 400, message = "参数错误"),
        @ApiResponse(code = 404, message = "资源不存在"),
        @ApiResponse(code = 500, message = "系统内部错误")
    })
    @PostMapping("/delete/{id}")
    public CommonResult<Void> delete(
            @ApiParam(value = "文章ID", required = true) @PathVariable Integer id) {
        boolean success = articleService.removeById(id);
        return success ? CommonResult.success(null, "删除成功") : CommonResult.failed("删除失败");
    }

    @ApiOperation(value = "分页查询文章", notes = "根据条件分页查询知识点文章列表")
    @ApiResponses({
        @ApiResponse(code = 200, message = "查询成功"),
        @ApiResponse(code = 500, message = "系统内部错误")
    })
    @GetMapping("/list")
    public CommonResult<CommonPage<KnowledgePointArticle>> list(
            @ApiParam(value = "一级分类ID") @RequestParam(value = "categoryOneId", required = false) Integer categoryOneId,
            @ApiParam(value = "二级分类ID") @RequestParam(value = "categoryTwoId", required = false) Integer categoryTwoId,
            @ApiParam(value = "搜索关键字") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "状态") @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(value = "页码", defaultValue = "1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value = "每页数量", defaultValue = "10") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<KnowledgePointArticle> queryWrapper = new LambdaQueryWrapper<>();
        // 显示指定要查询的字段，不包含content
        queryWrapper.select(
            KnowledgePointArticle::getId,
            KnowledgePointArticle::getCategoryOneId,
            KnowledgePointArticle::getCategoryTwoId,
            KnowledgePointArticle::getTitle,
            KnowledgePointArticle::getSummary,
            KnowledgePointArticle::getViewCount,
            KnowledgePointArticle::getUseCount,
            KnowledgePointArticle::getStatus,
            KnowledgePointArticle::getCreatedAt,
            KnowledgePointArticle::getUpdatedAt
        );
        
        if (categoryOneId != null) {
            queryWrapper.eq(KnowledgePointArticle::getCategoryOneId, categoryOneId);
        }
        if (categoryTwoId != null) {
            queryWrapper.eq(KnowledgePointArticle::getCategoryTwoId, categoryTwoId);
        }
        if (status != null) {
            queryWrapper.eq(KnowledgePointArticle::getStatus, status);
        }
        if (keyword != null) {
            queryWrapper.and(wrapper -> wrapper
                    .like(KnowledgePointArticle::getTitle, keyword)
                    .or()
                    .like(KnowledgePointArticle::getSummary, keyword));
        }
        queryWrapper.orderByDesc(KnowledgePointArticle::getCreatedAt);
        
        Page<KnowledgePointArticle> page = articleService.page(
                new Page<>(pageNum, pageSize),
                queryWrapper
        );
        return CommonResult.success(CommonPage.restPage(page));
    }

    @ApiOperation(value = "根据ID获取文章详情", notes = "根据ID获取知识点文章的详细信息")
    @ApiResponses({
        @ApiResponse(code = 200, message = "查询成功"),
        @ApiResponse(code = 404, message = "资源不存在"),
        @ApiResponse(code = 500, message = "系统内部错误")
    })
    @GetMapping("/{id}")
    public CommonResult<KnowledgePointArticle> getItem(
            @ApiParam(value = "文章ID", required = true) @PathVariable Integer id) {
        KnowledgePointArticle article = articleService.getDetailById(id);
        if (article == null) {
            return CommonResult.failed("文章不存在");
        }
        // 增加查看次数
        articleService.incrementViewCount(id);
        return CommonResult.success(article);
    }
    
    @ApiOperation(value = "增加文章使用次数", notes = "记录文章被使用的次数")
    @ApiResponses({
        @ApiResponse(code = 200, message = "操作成功"),
        @ApiResponse(code = 404, message = "资源不存在"),
        @ApiResponse(code = 500, message = "系统内部错误")
    })
    @PostMapping("/{id}/use")
    public CommonResult<Void> useArticle(
            @ApiParam(value = "文章ID", required = true) @PathVariable Integer id) {
        boolean success = articleService.incrementUseCount(id);
        return success ? CommonResult.success(null, "操作成功") : CommonResult.failed("操作失败");
    }
    
    @ApiOperation(value = "搜索文章", notes = "根据关键字搜索文章内容")
    @ApiResponses({
        @ApiResponse(code = 200, message = "查询成功"),
        @ApiResponse(code = 500, message = "系统内部错误")
    })
    @GetMapping("/search")
    public CommonResult<List<KnowledgePointArticle>> search(
            @ApiParam(value = "搜索关键字", required = true) @RequestParam(value = "keyword") String keyword) {
        List<KnowledgePointArticle> list = articleService.search(keyword);
        return CommonResult.success(list);
    }
}
